const express = require('express');
const router = express.Router();
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { BadRequestError, UnauthorizedError, NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

// 管理员注册
router.post('/sign_up', async (req, res) => {
    try {
        const body = {
            email: req.body.email,
            username: req.body.username,
            nickname: req.body.nickname,
            password: req.body.password,
            sex: 2,
            role: 0,
            // 可以添加更多默认或从请求体获取的字段赋值逻辑
        };

        const user = new User(body);
        await user.save();
        // 不返回密码字段给前端，保证安全性
        user.password = undefined;

        success(res, '创建用户成功。', { user }, 201);
    } catch (error) {
        console.error('注册错误详细信息：', error);
        failure(res, error);
    }
});

// 管理员登录
router.post('/sign_in', async (req, res) => {
    try {
        const { login, password } = req.body;

        if (!login) {
            throw new BadRequestError('邮箱/用户名必须填写。');
        }

        if (!login) {
            throw new BadRequestError('密码必须填写。');
        }

        // 查询用户是否存在，通过邮箱或者用户名查找
        const user = await User.findOne({
            $or: [
                { email: login },
                { username: login }
            ]
        });

        if (!user) {
            throw new NotFoundError('用户不存在，无法登录。');
        }

        // 验证密码是否正确
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            throw new UnauthorizedError('密码错误。');
        }

        // 生成 JWT 令牌，假设环境变量 SECRET 中存储了密钥
        const token = jwt.sign({
            userId: user._id
        }, process.env.SECRET, { expiresIn: '30d' });

        success(res, '登录成功。', { token, login, avatar: user.avatar, nickname: user.nickname });
    } catch (error) {
        failure(res, error);
    }
});

module.exports = router;